//
//  WZHCycleView.m
//  实训项目
//
//  Created by wszyxc on 16/5/18.
//  Copyright © 2016年 wszyxc. All rights reserved.
//

#import "WZHCycleView.h"

#define MAS_SHORTHAND
#define MAS_SHORTHAND_GLOBALS
#import "Masonry.h"

#import <UIImageView+WebCache.h>


@interface WZHCycleView ()<UIScrollViewDelegate>


@property (weak,nonatomic) WZHCycleView * cycleView;
@property (weak,nonatomic) UIScrollView * cycleScrollView;
@property (weak,nonatomic) UILabel * cycleLabel;
@property (weak,nonatomic) NSTimer * timer;
@property (assign,nonatomic) NSInteger  totalImageViewCount;
@property (weak,nonatomic) UIPageControl * pageControl;

@property (strong,nonatomic) NSArray * titleArray;
@property (strong,nonatomic) NSArray * imageArray;



@end


#define kViewSize  (self.bounds.size)

#define kDefautTimeDelay 1




@implementation WZHCycleView

/**
 *  在懒加载中实现对外界数据的加载
 *
 *  @return <#return value description#>
 */

- (NSArray *)imageArray{
    NSArray * kDefaultImageArray = @[@"banner",@"banner",@"banner",@"banner",@"banner"];
  
    if (nil == _imageArray) {
        
            NSLog(@"没有图片数据,加载假数据");
        _imageArray = [NSMutableArray arrayWithArray:kDefaultImageArray];
    
    }
    
    return _imageArray;
}

- (instancetype)init{
    
    if (self = [super init]) {
      //NSLog(@"%s",__func__);
        //证明这个初始化方法没有被调用
    }
    
    return self;
}



- (WZHCycleView *)initWithFrame:(CGRect)frame{
    
    
    if (self = [super initWithFrame:frame]) {
    
      //  NSLog(@"%s",__func__);
      //  self.backgroundColor = [UIColor yellowColor];/*****测试代码******/

        //向cycleView中添加子控件,这里调用setupUI,他的里面会调用imageArray的getter方法,而此时代理 还没有被设置,导致不会调用代理方法.
        
        [self setupUI];
        //布局子控件
        [self setupLayout];
        
        if (self.isAutoCycle) {
            [self startTimerWithTimeDelay:kDefautTimeDelay];
        }
        
    }

    
    return self;
    
}



+ (WZHCycleView *)wzhCycleViewWithFrame:(CGRect)frame{
    
    
    return [[self alloc]initWithFrame:frame];
    
}

- (void)layoutSubviews{
    [super layoutSubviews];
    

    
}


- (void)setupUI{
    

    /**
     1.添加scrollView
  
     */
    UIScrollView * cycleScrollView = [[UIScrollView alloc]init];
    self.cycleScrollView = cycleScrollView;
    
   // cycleScrollView.backgroundColor = [UIColor blueColor];/*****测试代码******/
    cycleScrollView.delegate = self;
    //更新数据
    [self updataScrollView];
    
    
  //  NSLog(@"%@",NSStringFromCGSize(cycleScrollView.contentSize));
    cycleScrollView.showsHorizontalScrollIndicator = NO;
    
    cycleScrollView.pagingEnabled = YES;
    
    
    [self addSubview:cycleScrollView];
    
    
    
    /**
     2.添加Label
     */
//    UILabel * cycleLabel = [[UILabel alloc]init];
//    
//    self.cycleLabel = cycleLabel;
//    _cycleLabel.font = [UIFont systemFontOfSize:15];
//    _cycleLabel.textColor = [UIColor whiteColor];
//    cycleLabel.backgroundColor = [UIColor redColor];/*****测试代码******/
//    cycleLabel.text = @"ceshi";/*****测试代码******/


//    [self addSubview:cycleLabel];
    
    //3.添加pageControl
    UIPageControl *pageControl = [[UIPageControl alloc]init];
    
    self.pageControl = pageControl;
    
    pageControl.currentPage = 0;
    pageControl.numberOfPages = self.imageArray.count;
    pageControl.pageIndicatorTintColor = [UIColor grayColor];
    pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    
    [self addSubview:pageControl];
}


- (void)updataScrollView{
    
    
    NSInteger imageViewCount = self.imageArray.count + 2;
    self.totalImageViewCount = imageViewCount;
    self.pageControl.numberOfPages = self.imageArray.count;
    //   _imageViewCount = 5;/*****测试代码******/
    _cycleScrollView.contentSize = CGSizeMake(imageViewCount * kViewSize.width, 0);
    _cycleScrollView.contentOffset = CGPointMake(kViewSize.width, 0);
    
    for (int i = 0; i<imageViewCount; i++) {
        CGRect imageFrame = CGRectMake(i * kViewSize.width, 0, kViewSize.width, kViewSize.height);
       
        UIImageView *disImageView = [[UIImageView alloc]initWithFrame:imageFrame];
        
        if (self.isNetImage) {
            //如果是网络图片
            NSString *urlStr;
            
            if (i == 0) {
                urlStr = _imageArray[_imageArray.count-1];
               
            }else if (i == imageViewCount - 1){
               urlStr = _imageArray[0];
            }else{
                
               urlStr = _imageArray[i-1];
            }
            
            [disImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"banner"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
            }];
            
        }else{
            //如果是本地图片
            if (i == 0) {
                disImageView.image = [UIImage imageNamed:_imageArray[_imageArray.count-1]];
            }else if (i == imageViewCount - 1){
                disImageView.image = [UIImage imageNamed:_imageArray[0]];
            }else{
                
                disImageView.image = [UIImage imageNamed:_imageArray[i-1]];
            }
            
        }
        
     
        
        [_cycleScrollView addSubview:disImageView];
    }

    
}





- (void)setupLayout{
    
    [self.cycleScrollView mas_makeConstraints:^(MASConstraintMaker *make){
       
        make.leading.trailing.top.bottom.offset(0);
        
    }];
    
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {

        make.centerX.equalTo(self.mas_centerX);
        make.bottom.offset(-3);
        
    }];
    
}


#pragma mark wzhCycleView的代理




#pragma mark - scrollView的代理

- (void)startTimerWithTimeDelay:(CGFloat)timeDelay{
    
    if (!timeDelay) {
        timeDelay = 1;
    }
    [self.timer invalidate];
    self.timer = nil;
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:timeDelay target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    self.timer = timer;
    
    [[NSRunLoop mainRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
}

- (void)stopTimer{
    
    [self.timer invalidate];
    self.timer = nil;
}

- (void)nextPage{
    
  //  NSLog(@"%s",__func__);

    
    //获取一个从0开始的当前页码,这个页码是所有的imageView的页码
    NSInteger currentPage = self.cycleScrollView.contentOffset.x / kViewSize.width;
    
    BOOL isAnimated;
    
    //判断一下获取到的当前页码,如果是所有imageView的最后一页,则不执行currentPage++的操作
    
    if (currentPage != _totalImageViewCount - 1 && currentPage != 0) {
        currentPage++;
        isAnimated = YES;
    }else{
        if (currentPage == _totalImageViewCount -1) {
            currentPage = 1;
        }else{
            currentPage = _totalImageViewCount-2;
        }
    }
    
        
    CGPoint targetPoint = CGPointMake(currentPage * kViewSize.width, 0);
        
    //NSLog(@"%ld",currentPage);
        
    [self.cycleScrollView setContentOffset:targetPoint animated:isAnimated];

}


- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    
    [self WZHScrollToRightPointAlsoUpdataPageControlAndSetTitleLabel];

    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [self stopTimer];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //只有手动拖拽减速停下来才会进入这个方法
//    NSLog(@"减速");
    
    [self WZHScrollToRightPointAlsoUpdataPageControlAndSetTitleLabel];
}



- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (self.isAutoCycle) {
        [self startTimerWithTimeDelay:_timeDelay];
    }
    
}



- (void)setDelegate:(id<wzhCycleViewDelegate>)delegate{
    
    _delegate = delegate;
    
    //设置好代理之后调用一次该方法,实现对scrollView的图片数据的更新
  
    if ([self.delegate respondsToSelector:@selector(imageArrayForWZHCycleView)]) {
        
        _imageArray = nil;
        
        _imageArray  = [self.delegate imageArrayForWZHCycleView];
        //刷新scrollview的数据
        [self updataScrollView];
        
    }
    
    //更新文本的数据源数据
    if ([self.delegate respondsToSelector:@selector(titleArrayForWZHCycleView)]) {
        
        _titleArray = [self.delegate titleArrayForWZHCycleView];
        
    }
   
}


- (void)setTimeDelay:(CGFloat)timeDelay{
    
    _timeDelay = timeDelay;
    if (timeDelay && self.isAutoCycle) {
         //启动定时器
        [self startTimerWithTimeDelay:timeDelay];
    }
   
}

- (void)setAutoCycle:(BOOL)autoCycle{
    
    _autoCycle = autoCycle;
    
    if (autoCycle) {
        [self startTimerWithTimeDelay:_timeDelay];
    }
    
    
}



/**
 *  当位置不在数据源的正常范围中,而在首尾添加的两个imageView上时,所做的位置修改.
 */
- (void)WZHScrollToRightPointAlsoUpdataPageControlAndSetTitleLabel{

    /**
     *让scrollView偷偷的滚回到适当的位置,也就是处理位置不适当时的位置修改
     */
    
    NSInteger currentImageViewIndex = _cycleScrollView.contentOffset.x / kViewSize.width;
    
    if (currentImageViewIndex >= _totalImageViewCount-1) {
        //如果当前显示的imageView为所有imageView的最后一个
        
        currentImageViewIndex = 1;
        
    }else if (currentImageViewIndex <= 0){
        currentImageViewIndex = _totalImageViewCount -2;
    }else ;
    
    [self.cycleScrollView setContentOffset:CGPointMake(currentImageViewIndex * kViewSize.width, 0) animated:NO];
    
    self.pageControl.currentPage = currentImageViewIndex -1;
    
    if(!_titleArray ){
        self.cycleLabel.text = _titleArray[currentImageViewIndex-1];
    }
}





@end
